import { ApiCall } from 'tsrpc'
import { ReqGetConfigs, ResGetConfigs } from '../shared/api_config_editor/PtlGetConfigs'
import { configManager } from '../config/ConfigManager'

export default async function (call: ApiCall<ReqGetConfigs, ResGetConfigs>) {
    try {
        const { type } = call.req
        
        let data: any[] = []
        
        switch (type) {
            case 'equipment':
                data = configManager.getAllEquipmentTemplates()
                break
                
            case 'skill':
                // 从configManager获取所有技能配置
                const skillStats = configManager.getSkillStats()
                // 这里需要实现获取技能列表的方法
                // 暂时返回空数组，待configManager实现getAllSkills方法
                data = []
                break
                
            default:
                // 尝试从配置文件中读取
                const fs = require('fs')
                const path = require('path')
                const configDir = path.resolve(__dirname, '../core/config')
                
                // 查找匹配的配置文件
                const files = fs.readdirSync(configDir)
                const matchingFile = files.find((file: string) => 
                    file.startsWith(type + '_') && file.endsWith('.json')
                )
                
                if (matchingFile) {
                    const filePath = path.join(configDir, matchingFile)
                    const content = fs.readFileSync(filePath, 'utf-8')
                    const jsonData = JSON.parse(content)
                    data = Array.isArray(jsonData) ? jsonData : [jsonData]
                } else {
                    call.error(`未找到配置类型: ${type}`)
                    return
                }
        }
        
        call.succ({
            data
        })
        
    } catch (error) {
        console.error(`Failed to get configs for type ${call.req.type}:`, error)
        call.error('获取配置失败', {
            errors: [(error as any).message]
        })
    }
}
